<?php

namespace App;

use App\Model;
use DB;
use Illuminate\Foundation\Auth\User as Authenticatable;

class SuperAgent extends Authenticatable
{
    protected $rememberTokenName = '';
    protected $guarded = [];
    protected $table = 'super_agent';
    
    /**
     * [totalRebate 超级代理产生的消费总额]
     * @return [type] [description]
     */
    public function totalRebate()
    {
    	$total_cash = 0;
    	$first_agents = Agent::where(['superagent_id' => $this->id])->get();//发展的一级代理
    	if ($first_agents) {
    		foreach ($first_agents as $f_agent) {
    			$second_agents = Agent::where(['pid' => $f_agent->id])->get();//二级代理
    			if ($second_agents) {
    				foreach ($second_agents as $s_agent) {
    					$second_users = User::where(['daili_id' => $s_agent->id])->get();//二级代理发展的用户
    					if ($second_users) {
    						foreach ($second_users as $s_user) {
    							$total_cash += Order::select(DB::raw('SUM(order_amount)'))->where(['type' => 1, 'pay_status' => 1, 'user_id' => $s_user->userid])->groupBy('order_sn')->value('SUM(order_amount)');
    						}
    					}
    				}
    			}
    			$first_users = User::where(['daili_id' => $f_agent->id])->get();//一级代理发展的用户
    			if ($first_users) {
    				foreach ($first_users as $f_user) {
    					$total_cash += Order::select(DB::raw('SUM(order_amount)'))->where(['type' => 1, 'pay_status' => 1, 'user_id' => $f_user->userid])->groupBy('order_sn')->value('SUM(order_amount)');
    				}
    			}
    		}
    	}
    	return $total_cash;
    }

    public function superTotalWithdraw()
    {
        $fee = Withdraw::select(DB::raw('SUM(money)'))->where(['agent_id' => $this->id, 'is_super' => 1 ])->whereIn('status', [0, 1])->value('SUM(money)');
        return $fee ? $fee : 0;
    }

    public function user()
    {
        return User::where(['account' => 'wx_'.$this->unionid])->first();
    }

}    